import axios from 'axios'
import Vue from 'vue'
import VueRouter from 'vue-router'
import { tip } from '../tools/tip'
import url from '../config/url'
Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    redirect:'/login'
  },
  {
    path:'/login',
    component:() => import('../views/Login.vue')
  },
  {
    path:'/register',
    component:()=>import('../views/Register.vue')
  },
  {
    path:'/admin',
    component:()=>import('../views/admin/Admin.vue'),
    meta:{
      isLogin:true
    },
    children:[
      {
        path:'users',
        component:()=>import('../views/admin/Users.vue'),
        meta:{
          isLogin:true
        },
      },
      {
        path:'goods',
        component:()=>import('../views/admin/Goods.vue'),
        meta:{
          isLogin:true
        },
      },
      {
        path:'dashboard',
        component:()=>import('../views/admin/Dashboard.vue'),
        meta:{
          isLogin:true
        },
      },
      {
        path:'index',
        component:()=>import('../views/admin/Index.vue'),
        meta:{
          isLogin:true
        },
      }
    ],
    // 路由独享守卫
    // beforeEnter:(to,from,next) => {
    //   if(!localStorage.getItem('token')){
    //     tip('请先登录','error')
    //     next('/login')
    //   }else{
    //     axios.get('http://localhost:5000/api/v1/profile').then(res=>{
    //       if(res.data.code === 401){
    //         tip('请先登录','error')
    //         next('/login')
    //       }else{
    //         localStorage.setItem('userInfo',JSON.stringify(res.data.data))
    //         next()
    //       }
    //     })
    //   }
    // }
  }
]
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 全局前置守卫
router.beforeEach((to,from,next) => {
  if(to.meta.isLogin){
    if(!localStorage.getItem('token')){
      tip('请先登录','error')
      next('/login')
    }else{
      axios.get(url.profile).then(res=>{
        if(res.data.code === 401){
          tip('请先登录','error')
          next('/login')
        }else{
          localStorage.setItem('userInfo',JSON.stringify(res.data.data))
          next()
        }
      })
    }
  }else{
    next()
  }
})


export default router
